package com.example.springboot_demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @Author: zt
 * @Date: 2021/5/21 14:23
 * @Description:
 */
@Controller
@Slf4j
public class FormTestController {

    /**
     * 测试 5xx 错误返回自定义页面的效果
     * @return
     */
    @GetMapping("/errTest")
    public String errTest() {
        int result = 10 / 0;
        return "main";
    }

    @GetMapping("/form_layouts")
    public String form_layouts() {
        return "/form/form_layouts";
    }

    /**
     * MultipartFile 自动封装上传的文件
     * @param email
     * @param username
     * @param avatar
     * @param fileUpload
     * @return
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("email") String email,
                         @RequestParam("username") String username,
                         @RequestPart("avatar") MultipartFile avatar,
                         @RequestPart("fileUpload") MultipartFile[] fileUpload) throws IOException {
        // avatar.getSize() 文件大小
        // fileUpload.length 上传文件的个数
        log.info("上传的信息：email={}, username={}, avatar={}, fileUpload={}",
                email, username, avatar.getSize(), fileUpload.length);

        if (!avatar.isEmpty()) {
            // 保存到服务器，OSS服务器
            String originalFilename = avatar.getOriginalFilename(); // 原始文件名
            avatar.transferTo(new File("F:\\project file\\" + originalFilename));
        }

        if (fileUpload.length > 0) {
            for (MultipartFile file : fileUpload) {
                if (!file.isEmpty()) {
                    String originalFilename = file.getOriginalFilename();
                    file.transferTo(new File("F:\\project file\\" + originalFilename));
                }
            }
        }

        return "main";
    }
}
